use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::process;

fn handle_client(mut stream: TcpStream) {
    let _ = stream.write(b"Hello World!");
}

fn listen_loop(mut listener: TcpListener) {
    /* Main loop goes here */
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                /* Gotya! */
                thread::spawn(move|| {
                    handle_client(stream);
                });
            }
            Err(e) => {
                /* Don't be too early to optimize?! */
                process::exit(1);
            }
        }
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:30599").unwrap();
    let loop_thread = thread::spawn(move|| {
        listen_loop(listener);
    });
    
    println!("Server listened at 127.0.0.1:30599");
    loop_thread.join();
}
